# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['FSRHostDisk']

class FSRHostDisk(Base, SessionMixin):
    '''
    生产业务服务弹性伸缩
    '''
    __tablename__ = "fsr_host_disk"
    name = Column(String(256), nullable=False, comment='服务器名称')
    ip = Column(String(24), nullable=False, comment='服务器ip地址')
    mountpoint = Column(String(256), default="all", comment='磁盘挂载目录')
    # 容器节点/物理服务/
    classes = Column(String(128), nullable=False, index=True, comment='服务器归类')
    # firing / resolved
    status = Column(String(16), default="resolved", index=True, comment='告警状态')
    # true/false
    state = Column(Boolean, default=text('true'), nullable=False, comment='使能状态')
    script = Column(String(256), nullable=False, comment='处理脚本的名称')
    update_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='服务器说明')


    __table_args__ = (
        Index('idx_fsr_host_disk_name', 'name'),
        Index('idx_fsr_host_disk_ip_mountpoint', 'ip', 'mountpoint', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<fsr_host_disk='{self.name}>"

    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }

        return result



    @classmethod
    def get_object_by_ip_allpoint(cls, db: Session, ip: str):
        """
        根据服务器ip，查找是否存在
        """
        object = db.query(cls).filter(
            cls.ip == ip,
            cls.mountpoint == "all"
        ).first()
        return object



    @classmethod
    def get_object_by_ip_mountpoint(cls, db: Session, ip: str, mountpoint: str):
        """
        根据服务器ip和挂载目录，查找是否存在
        """
        # 优先
        object = db.query(cls).filter(
            cls.ip == ip,
            cls.mountpoint == mountpoint
        ).first()


        return object



